(function() {

    'use strict';

    angular
        .module('app')
        .controller('GoodsController', GoodsController);

    GoodsController.$inject = ['$scope', '$http', '$window', '$timeout', 'CartModel', '$location', '$state', '$stateParams', 'API', 'ENUM'];

    function GoodsController($scope, $http, $window, $timeout, CartModel, $location, $state, $stateParams, API, ENUM) {

        var PER_PAGE = 10;
        var CURRENT_PAGE = 1;
        var TOTAL_PAGE = 1;

        $scope.currentCatID = $stateParams.cat_id;
        $scope.navTitle = $stateParams.navTitle;
        $scope.navStyle = $stateParams.navStyle;
        if (!$scope.navStyle) {
            $scope.navStyle = 'default';
        }

        $scope.goods_arr = null;
        $scope.isEmpty = false;
        $scope.isLoaded = false;
        $scope.isLoading = false;
        $scope.isLastPage = false;
        $scope.cartModel = CartModel;

        $scope.touchProduct = function(goods) {
            $state.go('goods-info', {
                goods_id: goods.goods_id
            });
        };
        $scope.loadMore = _loadMore;

        function _reload() {
            if ($scope.isLoading)
                return;

            $scope.goods_arr = null;
            $scope.isEmpty = false;
            $scope.isLoaded = false;

            _fetch(1, PER_PAGE);
        }

        function _loadMore() {
            if ($scope.isLoading)
                return;
            if ($scope.isLastPage)
                return;

            if (CURRENT_PAGE < TOTAL_PAGE) {
                _fetch(CURRENT_PAGE + 1, PER_PAGE);
            } else {
                _fetch(1, PER_PAGE);
            }
        }

        function _fetch(page, perPage) {
            $scope.isLoading = true;

            var params = {};

            if ($scope.currentCatID) {
                params.cat_id = $scope.currentCatID;
            }
            params.page = page;
            params.per_page = perPage;

            API.goods.getList(params).then(function(res) {
                $scope.goods_arr = $scope.goods_arr ? $scope.goods_arr.concat(res.rows) : res.rows;
                $scope.isEmpty = res.total ? false : true;
                $scope.isLoaded = true;
                $scope.isLoading = false;
                $scope.isLastPage = res.current_page==res.total_page ? !$scope.isEmpty : false;
                CURRENT_PAGE = res.current_page;
                TOTAL_PAGE = res.total_page;
            });
        }

        _reload();
    }

})();
